package com.liruo.treasureattic.common.model.vo.url;

import lombok.Data;
import lombok.ToString;

import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:liruo
 * @Date:2022-12-13-19:59:04
 * @Desc
 */
@ToString
@Data
public class UrlFolderVo implements Serializable {
    @Serial
    private static final long serialVersionUID = -7683270361843140968L;
    private Long id;
    /**
     * All secondary fid should be the default folder.
     *  or url
     *  fid = 1 is a default url folder
     */
    private Long fid;
    /**
     * max=128
     */
    private String name;
    private Boolean open;
    /**
     * createdTime
     */
    private Date created;
    /**
     * updateTime
     */
    private Date updated;


    private List<UrlVo> urlVos = new LinkedList<>();
    private List<UrlFolderVo> subFolders = new LinkedList<>();

    public void addUrl(UrlVo urlVo) {
        this.urlVos.add(urlVo);
    }
    public void addSubFolder(UrlFolderVo subFolder) {
        this.subFolders.add(subFolder);
    }

    public static List<UrlFolderVo>  build(List<UrlVo> urls, List<UrlFolderVo> folders) {
        Map<Long, List<UrlVo>> urlMap = urls.stream()
                .collect(Collectors.groupingBy(UrlVo::getFid));
        folders.stream()
                .filter(folder->urlMap.containsKey(folder.getId()))
                .forEach(folder->folder.setUrlVos(urlMap.get(folder.getId())));

        Map<Long, List<UrlFolderVo>> subFolderMap = folders.stream()
                .collect(Collectors.groupingBy(UrlFolderVo::getFid));
        return folders.stream()
                .filter(folder -> subFolderMap.containsKey(folder.getId()))
                .peek(folder -> folder.setSubFolders(subFolderMap.get(folder.getId())))
                .toList();
    }
}
